import json
import datetime
import functools
from decimal import Decimal
DATE_FORMAT = "%Y%m%d"

d2id = lambda x: int(x.strftime(DATE_FORMAT))
id2d = lambda x: datetime.datetime.strptime(str(x), DATE_FORMAT)
round3 = functools.partial(round, ndigits=3)

def deep_json_loads(data):
    """深度使用json.loads"""
    if isinstance(data, dict):
        for k, v in data.items():
            data[k] = deep_json_loads(v)
        return data
    elif isinstance(data, list):
        return [deep_json_loads(i) for i in data]
    elif isinstance(data, str):
        if data.startswith("[{") or data.startswith("{"):
            if data.find('"') == -1:
                data = data.replace("'", '"')
            return deep_json_loads(json.loads(data))
        elif data.startswith("["):
            return deep_json_loads(eval(data))
        else:
            return data
    elif isinstance(data, int) or isinstance(data, float):
        return data
    else:
        raise Exception("数据格式不正确, deep_json_loads失败")


def key_rename(map: dict, k2k: dict) -> dict:
    """更换字典的主键值

    Args:
        map (dict): 原映射
        k2k (dict): 主键应射
    """
    return {v: map.get(k) for k, v in k2k}


def pretty_data(obj):
    '''转换数据'''
    if isinstance(obj, float):
        return round(obj, 4)
    elif isinstance(obj, datetime.datetime):
        return obj.strftime('%Y-%m-%d %H:%M:%S')
    elif isinstance(obj, Decimal):
        return round(float(obj), 4)
    elif isinstance(obj, datetime.date):
        return obj.strftime("%Y-%m-%d")
    elif isinstance(obj, dict):
        return dict((pretty_data(k), pretty_data(v)) for k, v in obj.items())
    elif isinstance(obj, (list, tuple)):
        return [pretty_data(i) for i in obj]
    return obj
